package com.talkweb.citypickerview.style.citycustome;


import com.talkweb.citypickerview.Interface.OnCustomCityPickerItemClickListener;
import com.talkweb.citypickerview.ResourceTable;
import com.talkweb.citypickerview.bean.CustomCityData;
import com.talkweb.citypickerview.citywheel.CustomConfig;
import com.talkweb.citypickerview.style.citylist.Toast.ToastUtils;
import com.talkweb.citypickerview.style.citypickerview.widget.CanShow;
import com.talkweb.citypickerview.style.citypickerview.widget.wheel.WheelPicker;
import com.talkweb.citypickerview.utils.TextUtils;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;

import java.util.List;

public class CustomCityPicker implements CanShow, Picker.ValueChangedListener {


    private CommonDialog popwindow;

    private Component popview;

    private WheelPicker mViewProvince;

    private WheelPicker mViewCity;

    private WheelPicker mViewDistrict;

    private Context mContext;

    private DependentLayout mRelativeTitleBg;

    private Text mTvOK;

    private Text mTvTitle;

    private Text mTvCancel;

    private CustomConfig config;

    private OnCustomCityPickerItemClickListener listener = null;

    private CustomConfig.WheelType type = CustomConfig.WheelType.PRO_CITY_DIS;

    public void setOnCustomCityPickerItemClickListener(OnCustomCityPickerItemClickListener listener) {
        this.listener = listener;
    }

    public CustomCityPicker(Context context) {
        this.mContext = context;
    }

    public void setCustomConfig(CustomConfig config) {
        this.config = config;
    }

    private void initView() {
        if (config == null) {
            ToastUtils.showLongToast(mContext, "请设置相关的config");
            return;
        }

        LayoutScatter layoutInflater = LayoutScatter.getInstance(mContext);
        popview = layoutInflater.parse(ResourceTable.Layout_pop_citypicker, null, false);

        mViewProvince = (WheelPicker) popview.findComponentById(ResourceTable.Id_id_province);
        mViewCity = (WheelPicker) popview.findComponentById(ResourceTable.Id_id_city);
        mViewDistrict = (WheelPicker) popview.findComponentById(ResourceTable.Id_id_district);

        mRelativeTitleBg = (DependentLayout) popview.findComponentById(ResourceTable.Id_rl_title);
        mTvOK = (Text) popview.findComponentById(ResourceTable.Id_tv_confirm);
        mTvTitle = (Text) popview.findComponentById(ResourceTable.Id_tv_title);
        mTvCancel = (Text) popview.findComponentById(ResourceTable.Id_tv_cancel);

        popwindow = new CommonDialog(mContext);
        popwindow.setContentCustomComponent(popview);
        popwindow.setAutoClosable(true);

        //设置显示层级
        type = config.getWheelType();
        setWheelShowLevel(type);

        /**
         * 设置标题背景颜色
         */
        if (!TextUtils.isEmpty(config.getTitleBackgroundColorStr())) {
            if (config.getTitleBackgroundColorStr().startsWith("#")) {
                ShapeElement shapeElement = new ShapeElement();
                shapeElement.setRgbColor(new RgbColor(Color.getIntColor(config.getTitleBackgroundColorStr())));
                mRelativeTitleBg.setBackground(shapeElement);
            } else {
                ShapeElement shapeElement = new ShapeElement();
                shapeElement.setRgbColor(new RgbColor(Color.getIntColor("#" + config.getTitleBackgroundColorStr())));
                mRelativeTitleBg.setBackground(shapeElement);
            }
        }

        //标题
        if (!TextUtils.isEmpty(config.getTitle())) {
            mTvTitle.setText(config.getTitle());
        }

        //标题文字大小
        if (config.getTitleTextSize() > 0) {
            mTvTitle.setTextSize(config.getTitleTextSize(), Text.TextSizeType.FP);
        }

        //标题文字颜色
        if (!TextUtils.isEmpty(config.getTitleTextColorStr())) {
            if (config.getTitleTextColorStr().startsWith("#")) {
                mTvTitle.setTextColor(new Color(Color.getIntColor(config.getTitleTextColorStr())));
            } else {
                mTvTitle.setTextColor(new Color(Color.getIntColor("#" + config.getTitleTextColorStr())));
            }
        }

        //设置确认按钮文字大小颜色
        if (!TextUtils.isEmpty(config.getConfirmTextColorStr())) {
            if (config.getConfirmTextColorStr().startsWith("#")) {
                mTvOK.setTextColor(new Color(Color.getIntColor(config.getConfirmTextColorStr())));
            } else {
                mTvOK.setTextColor(new Color(Color.getIntColor("#" + config.getConfirmTextColorStr())));
            }
        }

        if (!TextUtils.isEmpty(config.getConfirmText())) {
            mTvOK.setText(config.getConfirmText());
        }

        if ((config.getConfirmTextSize() > 0)) {
            mTvOK.setTextSize(config.getConfirmTextSize(), Text.TextSizeType.FP);
        }

        //设置取消按钮文字颜色
        if (!TextUtils.isEmpty(config.getCancelTextColorStr())) {
            if (config.getCancelTextColorStr().startsWith("#")) {
                mTvCancel.setTextColor(new Color(Color.getIntColor(config.getCancelTextColorStr())));
            } else {
                mTvCancel.setTextColor(new Color(Color.getIntColor("#" + config.getCancelTextColorStr())));
            }
        }

        if (!TextUtils.isEmpty(config.getCancelText())) {
            mTvCancel.setText(config.getCancelText());
        }

        if ((config.getCancelTextSize() > 0)) {
            mTvCancel.setTextSize(config.getCancelTextSize(), Text.TextSizeType.FP);
        }

        // 添加change事件
        mViewProvince.setValueChangedListener(this);
        // 添加change事件
        mViewCity.setValueChangedListener(this);
        // 添加change事件
        mViewDistrict.setValueChangedListener(this);
        // 添加onclick事件
        mTvCancel.setClickedListener(v -> {
            listener.onCancel();
            hide();
        });

        //确认选择
        mTvOK.setClickedListener(v -> {

            if (type == CustomConfig.WheelType.PRO) {
                int pCurrent = mViewProvince.getValue();
                List<CustomCityData> provinceList = config.getCityDataList();
                CustomCityData province = provinceList.get(pCurrent%provinceList.size());
                listener.onSelected(province, new CustomCityData(), new CustomCityData());
            } else if (type == CustomConfig.WheelType.PRO_CITY) {
                int pCurrent = mViewProvince.getValue();
                List<CustomCityData> provinceList = config.getCityDataList();
                CustomCityData province = provinceList.get(pCurrent%provinceList.size());
                int cCurrent = mViewCity.getValue();
                List<CustomCityData> cityDataList = province.getList();
                if (cityDataList == null) {
                    return;
                }
                CustomCityData city = cityDataList.get(cCurrent%cityDataList.size());
                listener.onSelected(province, city, new CustomCityData());
            } else if (type == CustomConfig.WheelType.PRO_CITY_DIS) {
                int pCurrent = mViewProvince.getValue();
                List<CustomCityData> provinceList = config.getCityDataList();
                CustomCityData province = provinceList.get(pCurrent%provinceList.size());
                int cCurrent = mViewCity.getValue();
                List<CustomCityData> cityDataList = province.getList();
                if (cityDataList == null) {
                    return;
                }
                CustomCityData city = cityDataList.get(cCurrent%cityDataList.size());
                int dCurrent = mViewDistrict.getValue();
                List<CustomCityData> areaList = city.getList();
                if (areaList == null) {
                    return;
                }
                CustomCityData area = areaList.get(dCurrent%areaList.size());
                listener.onSelected(province, city, area);
            }

            hide();
        });

        //背景半透明
        if (config != null && config.isShowBackground()) {
            popwindow.setTransparent(config.isShowBackground());
        }

        //显示省市区数据
        setUpData();
    }

    /**
     * 显示省市区等级
     *
     * @param type
     */
    private void setWheelShowLevel(CustomConfig.WheelType type) {
        if (type == CustomConfig.WheelType.PRO) {
            mViewProvince.setVisibility(Component.VISIBLE);
            mViewCity.setVisibility(Component.HIDE);
            mViewDistrict.setVisibility(Component.HIDE);
        } else if (type == CustomConfig.WheelType.PRO_CITY) {
            mViewProvince.setVisibility(Component.VISIBLE);
            mViewCity.setVisibility(Component.VISIBLE);
            mViewDistrict.setVisibility(Component.HIDE);
        } else {
            mViewProvince.setVisibility(Component.VISIBLE);
            mViewCity.setVisibility(Component.VISIBLE);
            mViewDistrict.setVisibility(Component.VISIBLE);
        }
    }

    private void setUpData() {
        List<CustomCityData> proArra = config.getCityDataList();
        if (proArra == null) {
            return;
        }

        int provinceDefault = 0;
        if (!TextUtils.isEmpty(config.getDefaultProvinceName()) && proArra.size() > 0) {
            for (int i = 0; i < proArra.size(); i++) {
                if (proArra.get(i).getName().startsWith(config.getDefaultProvinceName())) {
                    provinceDefault = i;
                    break;
                }
            }
        }

        mViewProvince.setDisplayedData(proArra);
        mViewProvince.setMaxValue(proArra.size());
        //获取所设置的省的位置，直接定位到该位置
        mViewProvince.setValue(provinceDefault);

        // 设置可见条目数量
        mViewProvince.setSelectorItemNum(config.getVisibleItems());
        mViewCity.setSelectorItemNum(config.getVisibleItems());
        mViewDistrict.setSelectorItemNum(config.getVisibleItems());

        //配置循环状态
        mViewProvince.setWheelModeEnabled(config.isProvinceCyclic());
        mViewCity.setWheelModeEnabled(config.isCityCyclic());
        mViewDistrict.setWheelModeEnabled(config.isDistrictCyclic());

        //中间线的颜色及高度
        ShapeElement shape = new ShapeElement();
        shape.setShape(ShapeElement.RECTANGLE);
        shape.setStroke(config.getLineHeigh(),
                new RgbColor(AttrHelper.convertValueToColor(config.getLineColor()).getValue()));

        mViewProvince.setDisplayedLinesElements(shape, shape);
        mViewCity.setDisplayedLinesElements(shape, shape);
        mViewDistrict.setDisplayedLinesElements(shape, shape);

        if (type == CustomConfig.WheelType.PRO_CITY || type == CustomConfig.WheelType.PRO_CITY_DIS) {
            updateCities();
        }
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        //省份滚轮滑动的当前位置
        int pCurrent = mViewProvince.getValue();

        //省份选中的名称
        List<CustomCityData> proArra = config.getCityDataList();

        CustomCityData mProvinceBean = proArra.get(pCurrent%proArra.size());

        List<CustomCityData> pCityList = mProvinceBean.getList();
        if (pCityList == null) {
            return;
        }

        //设置最初的默认城市
        int cityDefault = -1;
        if (!TextUtils.isEmpty(config.getDefaultCityName()) && pCityList.size() > 0) {
            for (int i = 0; i < pCityList.size(); i++) {
                if (pCityList.get(i).getName().startsWith(config.getDefaultCityName())) {
                    cityDefault = i;
                    break;
                }
            }
        }

        if (-1 != cityDefault) {
            mViewCity.setValue(cityDefault);
        } else {
            mViewCity.setValue(0);
        }

        mViewCity.setDisplayedData(pCityList);
        mViewCity.setMaxValue(pCityList.size());
        if (type == CustomConfig.WheelType.PRO_CITY_DIS) {
            updateAreas();
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewProvince.getValue();
        int cCurrent = mViewCity.getValue();

        List<CustomCityData> provinceList = config.getCityDataList();

        CustomCityData province = provinceList.get(pCurrent % provinceList.size());
        List<CustomCityData> cityDataList = province.getList();
        if (cityDataList == null){
            return;
        }
        CustomCityData city = cityDataList.get(cCurrent%cityDataList.size());
        List<CustomCityData> areaList = city.getList();
        if (areaList == null) {
            return;
        }

        int districtDefault = 0;
        if (!TextUtils.isEmpty(config.getDefaultDistrict()) && areaList.size() > 0) {
            for (int i = 0; i < areaList.size(); i++) {
                if (areaList.get(i).getName().startsWith(config.getDefaultDistrict())) {
                    districtDefault = i;
                    break;
                }
            }
        }

        //设置默认城市
        mViewDistrict.setValue(districtDefault);
        mViewDistrict.setDisplayedData(areaList);
        mViewDistrict.setMaxValue(areaList.size());
    }

    public void showCityPicker() {
        initView();
        if (!isShow()) {
            popwindow.show();
        }
    }

    @Override
    public void hide() {
        if (isShow()) {
            popwindow.hide();
        }
    }

    @Override
    public boolean isShow() {
        return popwindow.isShowing();
    }

    @Override
    public void onValueChanged(Picker picker, int oldValue, int newValue) {
        if (picker == mViewProvince) {
            updateCities();
        } else if (picker == mViewCity) {
            updateAreas();
        }
    }
}
